const express = require('express');
const mysql = require('mysql2');
const path = require('path');

const app = express();
const port = process.env.PORT || 3000;
const host = '0.0.0.0';

// 添加日志中间件
app.use((req, res, next) => {
  console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`);
  console.log('请求头:', req.headers);
  next();
});

// 添加响应头中间件
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  res.header('Cache-Control', 'no-cache, no-store, must-revalidate');
  res.header('Pragma', 'no-cache');
  res.header('Expires', '0');
  next();
});

// 添加OPTIONS请求处理
app.options('*', (req, res) => {
  res.sendStatus(200);
});

// 添加测试路由
app.get('/test', (req, res) => {
  res.send('服务器运行正常！');
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error('发生错误:', err);
  res.status(500).json({ error: '服务器内部错误', details: err.message });
});

// 创建数据库连接池
const pool = mysql.createPool({
  host: process.env.DB_HOST || 'mysql',
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || 'root',
  database: process.env.DB_NAME || 'todos',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,
  connectTimeout: 60000
});

// 将连接池转换为promise形式
const promisePool = pool.promise();

// 初始化数据库
async function initDatabase() {
  let retries = 30; // 最多重试30次
  while (retries > 0) {
    try {
      // 创建todos表
      await promisePool.query(`
        CREATE TABLE IF NOT EXISTS todos (
          id INT AUTO_INCREMENT PRIMARY KEY,
          title VARCHAR(255) NOT NULL,
          completed BOOLEAN DEFAULT false,
          created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
      `);
      console.log('数据库初始化成功');
      return;
    } catch (err) {
      retries--;
      if (retries === 0) {
        console.error('数据库初始化失败，已达到最大重试次数:', err);
        process.exit(1);
      }
      console.log(`数据库连接失败，正在重试...（剩余 ${retries} 次尝试）`);
      await new Promise(resolve => setTimeout(resolve, 1000)); // 等待1秒后重试
    }
  }
}

app.use(express.json());
app.use(express.static('public'));

// API 端点

// 获取所有待办事项
app.get('/api/todos', async (req, res) => {
  try {
    let search = req.query.search ? decodeURIComponent(req.query.search).trim() : '';
    
    // 防止SQL注入，使用参数化查询
    const query = search
      ? `SELECT * FROM todos WHERE title LIKE ? ORDER BY created_at DESC`
      : `SELECT * FROM todos ORDER BY created_at DESC`;
    
    // 使用通配符进行模糊搜索，并转义特殊字符
    const searchPattern = search ? `%${search.replace(/%/g, '\\%').replace(/_/g, '\\_')}%` : null;
    const params = search ? [searchPattern] : [];
    
    console.log('执行查询:', query, '参数:', params); // 调试日志
    
    const [rows] = await promisePool.query(query, params);
    res.json(rows);
  } catch (err) {
    console.error('获取待办事项失败:', err);
    res.status(500).json({ error: '获取待办事项失败', details: err.message });
  }
});

// 添加新待办事项
app.post('/api/todos', async (req, res) => {
  const { title } = req.body;
  if (!title || title.trim() === '') {
    return res.status(400).json({ error: "标题不能为空" });
  }

  try {
    const [result] = await promisePool.query(
      'INSERT INTO todos (title, completed) VALUES (?, ?)',
      [title.trim(), 0]
    );
    
    const [newTodo] = await promisePool.query(
      'SELECT * FROM todos WHERE id = ?',
      [result.insertId]
    );
    
    res.json(newTodo[0]);
  } catch (err) {
    console.error('创建待办事项失败:', err);
    res.status(500).json({ error: '创建待办事项失败', details: err.message });
  }
});

// 更新待办事项
app.put('/api/todos/:id', async (req, res) => {
  const { title, completed } = req.body;
  const { id } = req.params;

  if (!id || isNaN(id)) {
    return res.status(400).json({ error: "无效的ID" });
  }

  try {
    let query = 'UPDATE todos SET';
    const updates = [];
    const params = [];

    if (title !== undefined) {
      if (title.trim() === '') {
        return res.status(400).json({ error: "标题不能为空" });
      }
      updates.push(' title = ?');
      params.push(title.trim());
    }
    
    if (completed !== undefined) {
      updates.push(' completed = ?');
      params.push(completed ? 1 : 0);
    }

    if (updates.length === 0) {
      return res.status(400).json({ error: "没有提供要更新的内容" });
    }

    query += updates.join(',');
    query += ' WHERE id = ?';
    params.push(id);

    const [result] = await promisePool.query(query, params);
    
    if (result.affectedRows === 0) {
      return res.status(404).json({ error: "待办事项不存在" });
    }
    
    res.json({ message: "更新成功" });
  } catch (err) {
    console.error('更新待办事项失败:', err);
    res.status(500).json({ error: '更新待办事项失败', details: err.message });
  }
});

// 删除待办事项
app.delete('/api/todos/:id', async (req, res) => {
  const { id } = req.params;
  
  if (!id || isNaN(id)) {
    return res.status(400).json({ error: "无效的ID" });
  }

  try {
    const [result] = await promisePool.query('DELETE FROM todos WHERE id = ?', [id]);
    
    if (result.affectedRows === 0) {
      return res.status(404).json({ error: "待办事项不存在" });
    }
    
    res.json({ message: "删除成功" });
  } catch (err) {
    console.error('删除待办事项失败:', err);
    res.status(500).json({ error: '删除待办事项失败', details: err.message });
  }
});

// 初始化数据库并启动服务器
initDatabase().then(() => {
  app.listen(port, host, () => {
    console.log(`服务器已启动，访问地址: http://${host}:${port}`);
  });
}); 